home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9435 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  52 lines

  1. Path: druid.borland.com!usenet
  2. From: pete@borland.com (Pete Becker)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: STL: for_each vs transform
  5. Date: 1 Mar 1996 18:12:44 GMT
  6. Organization: Borland International
  7. Message-ID: <4h7ems$6v@druid.borland.com>
  8. References: <3135F631.41C6@austin.ibm.com>
  9. NNTP-Posting-Host: pbecker.borland.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <3135F631.41C6@austin.ibm.com>, leou@austin.ibm.com says...
  15. >
  16. >How can iterate thru a container, using for_each, and apply a function
  17. >object which modifies each of the elements in the container?
  18. >I tried passing the argument by name, but the template definition
  19. >will not allow it.
  20. >
  21. >Here's the example: Note addr and size values never change.
  22. >
  23. >#include    <iostream.h>
  24. >#include    <algo.h>
  25. >#include    <vector.h>
  26. >
  27. >struct S { vector<int> v; };
  28. >struct g : public binary_function<S,int,int> {
  29. >    int operator()(S s,int x) const
  30. >    {s.v.push_back(x);
  31. >    cout<<"x="<<x<<endl;
  32. >    cout<<"g() addr of s:"<<(size_t)&s<<" size of v:"<<s.v.size()<<endl;
  33. >    return 0;};
  34. >};
  35. >
  36. >void main() {
  37. >vector<S> A(3); // A has 3 vector<int>'s
  38. >for (int i=0; i<2; i++)
  39. >    for_each( A.begin(),A.end(), bind2nd(g(),i) );
  40. >}
  41.  
  42. I made three changes in the first few lines of this code. None of them affect 
  43. the legality of the call to for_each. With those changes, this code compiled 
  44. just fine with BC++ 5.0. Here are the changed lines:
  45.  
  46. #include    <iostream.h>
  47. #include    <algorothm>        // 1: ANSI/ISO header name
  48. #include    <vector>        // 2: ANSI/ISO header name
  49.  
  50. using namespace std;        // 3: these things live in namespace std
  51.  
  52.